<?php

/**
 * GrouponController is the default controller for this application
 */
class GrouponController extends ControllerBase {
	
	/**
	 * Admin Groupon Data Service Object
	 * @var grouponDataService object
	 */
	private $grouponDataService;
	private $dealsDataService;
	public $grouponCategoryDataService = null;
	/**
	 *
	 * UsersDataService Object
	 * @var UsersDataService object
	 */
	public $userDataService = null;
	/**
	 * GrouponController Constructor
	 */
	public function __construct() {
		parent::__construct ();
		
		// Set groupon name
		$this->setPageName ( 'admin_groupon' );
		
		// Init Authentication class
		$authentication = new Authentication ();
		
		// Only administrator can right
		if (!($authentication->isAdministrator () == true || $authentication->getUserType() == ROLE_DEALMANAGER)) {
			// Go to login groupon
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/';
			CommonUtils::redirect ( $url );
		}
		
		// Get status list of groupon category
		//		$this->smarty->assign('statusList', GrouponEntity::getStatusList());
		

		// New groupon Data Service
		$this->grouponDataService = new GrouponDataService ();
		// new groupon category Data Service
		$this->grouponCategoryDataService = new GrouponCategoryDataService ();
		// New deals Data Service
		$this->dealsDataService = new DealsDataService ();
		$this->smarty->assign('pageName', 'groupon');
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing groupon of the site. Return list of all groupon category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function indexAction() {
		// View groupon_category list
		$this->listAction ();
	}
	
	/**
	 * Dispplay List of groupon_category
	 * landing groupon of the site. Return list of all groupon_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function listAction() {
		
		$arrElement = array ();
		//        $arrElement['status'] = grouponEntity::ACTIVE;
		

		$numRecordPerPage = ITEM_PER_PAGE;
		
		// Pager
		$start = $this->getQuery ( 'start', 0 );
		if ($start == '' || $start < 0) {
			$start = 0;
		}
		
		// Get Totals Templates
		$totals = $this->grouponDataService->getTotals ( $arrElement );
		
		$itemList = $this->grouponDataService->getItems ( $arrElement, 'id desc', $start, $numRecordPerPage );
		
		if ($start > $totals) {
			$start = 0;
		}
		$link = Zend_Registry::get ( 'config' )->APPLICATION_URL . "/Admin/Groupon/Index";
		$pageLink = '';
		if ($totals > $numRecordPerPage) {
			$pageUtils = new PagerUtils ( $start, $totals, $numRecordPerPage, 10, $link );
			$pageLink = $pageUtils->writePagesLinks ( 0, 'start' );
			$pageLink .= "<br><span class=\"paing_text_nolink\">" . $pageUtils->writePagesCounter () . "</span>";
		}
		
		$this->smarty->assign ( 'grouponEntities', $itemList );
		$this->smarty->assign ( 'this', $this );
		$this->smarty->assign ( 'pageLink', $pageLink );
		
		// create session
		$this->createActionKey ();
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Groupon/index.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Add action is trigger when admin want to add the groupon_category information
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function addAction() {
		$authentication = new Authentication();
		$isError = false;
		$msg = "";
		$aError = array();
		$bError = false;
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->validateActionKey ()) {
			$listAdds = $this->getPost ( 'address_related', array () );
			if(empty($listAdds)){
				$bError =  true;
				$aError = array_merge($aError, array('Chọn địa điểm'));
			}
			//Groupon
			// Get name field
			$groupon_name = $this->getPost ( 'groupon_name', "" );
			if($groupon_name == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Điền tên groupon'));
			}
			$groupon_name = trim ( $groupon_name );
			
			$category_id = $this->getPost ( 'category_id', 0 );
			if($category_id == 0){
				$bError =  true;
				$aError = array_merge($aError, array('Chọn thể loại'));
			}
			$supplier_id = $this->getPost ( 'supplier_id', 0 );
			if($supplier_id == 0){
				$bError =  true;
				$aError = array_merge($aError, array('Chọn nhà cung cấp'));
			}
			$title = $this->getPost ( 'title', "" );
			if($title == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Tiêu đề không bỏ trống'));
			}
			$title = trim ( $title );
			
			// get descriptopn
			$description = $this->getPost ( 'description', "" );
			if($description == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Giới thiệu không bỏ trống'));
			}
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$description = stripslashes ( $description );
			}
			$description = trim ( $description );
			// get hightlight
			$hightlight = $this->getPost ( 'hightlight', "" );
			if($hightlight == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Điểm nổi bật không bỏ trống'));
			}
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$hightlight = stripslashes ( $hightlight );
			}
			
			$hightlight = trim ( $hightlight );
			// Upload picture
			$picture = '';
			try {
				$picture = CommonUtils::uploadPictureEx ( 'picture' );
			} catch ( Exception $ex ) {
				// Ignore this case
				$resultMessage = 'Up ảnh lỗi.';
			}
			if($picture == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Chọn ảnh chính'));
			}
			//DEAL
			//du lieu rac, can xem lai
			//
			//
			$deal_name = 'test1';
			$address_id = 1;
			
			// get fine_print
			$fine_print = $this->getPost ( 'fine_print', "" );
			if($fine_print == ''){
				$bError =  true;
				$aError = array_merge($aError, array('Diều kiện mua hàng không bỏ trống'));
			}
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$fine_print = stripslashes ( $fine_print );
			}
			$fine_print = trim ( $fine_print );
			
			//get original_price
			$original_price = $this->getPost ( 'original_price', 0 );
			if(!is_numeric($original_price) ){
				$bError =  true;
				$aError = array_merge($aError, array('Giá gốc phải là số và lớn hơn 0'));
			};
			//get $sale_price
			$sale_price = $this->getPost ( 'sale_price', 0 );
			if(!is_numeric($sale_price) || !(intval($sale_price) > 0) || !(intval($sale_price) < intval($original_price))){
				$bError =  true;
				$aError = array_merge($aError, array('Giá bán phải là số, lớn hơn 0 và nhỏ hơn giá gốc'));
			}
//			//get sale_price
//			$sale_price = $original_price - $customer_discount;
			// get min_bought
			$min_bought = $this->getPost ( 'min_bought', 0 );
			if(!is_numeric($min_bought) || !(intval($min_bought) > 0)){
				$bError =  true;
				$aError = array_merge($aError, array('Số lượng bán tối thiểu phải là số và lớn hơn 0'));
			}
			//get max_bought
			$max_bought = $this->getPost ( 'max_bought', 0 );
			if(!is_numeric($max_bought) || !(intval($max_bought) >= intval($min_bought))){
				$bError =  true;
				$aError = array_merge($aError, array('Số lượng bán tối đa phải là số và lớn hơn số lượng bán tối thiểu'));
			}
			// get duration
			$duration = $this->getPost ( 'duration', 0 );
			if(!is_numeric($duration) || !(intval($duration) > 0)){
				$bError =  true;
				$aError = array_merge($aError, array('Thời gian bán phải là số và lớn hơn 0'));
			}
			//Action
			// check
			if (! empty ( $title ) && ! empty ( $description ) && !$bError) {
				try {
					
					// Init Authentication class
					$authentication = new Authentication ();
					//
					//Groupon
					//
					// Save data into database
					$grouponEntity = $this->grouponDataService->beforeCreate ();
					$grouponEntity->groupon_name = strval ( $groupon_name );
					$grouponEntity->category_id = ( int ) ($category_id);
					$grouponEntity->supplier_id = ( int ) ($supplier_id);
					$grouponEntity->title = strval ( $title );
					$grouponEntity->description = strval ( $description );
					$grouponEntity->hightlight = strval ( $hightlight );
					$grouponEntity->creation_date = date ( 'Y-m-d h:i:s' );
					$grouponEntity->modified_date = date ( 'Y-m-d h:i:s' );
					$grouponEntity->picture = strval ( $picture );
					$grouponEntity->city_id = 1;
					$grouponId = $this->grouponDataService->create ( $grouponEntity );
					//
					//DEAL
					//
					$dealsEntity = $this->dealsDataService->beforeCreate ();
					$dealsEntity->groupon_id = $grouponId;
					$dealsEntity->deal_name = $deal_name;
					$dealsEntity->address_id = $address_id;
					$dealsEntity->fine_print = $fine_print;
					$dealsEntity->original_price = $original_price;
					$dealsEntity->sale_price = $sale_price;
					$dealsEntity->bought_count = 0;
					$dealsEntity->started_deal = '';
					$dealsEntity->expired_deal = '';
					$dealsEntity->tipped_date = '';
					$dealsEntity->rating_average = 0;
					$dealsEntity->rating_count = 0;
					$dealsEntity->comment_count = 0;
					$dealsEntity->payment_type = 'test';
					$dealsEntity->min_bought = $min_bought;
					$dealsEntity->max_bought = $max_bought;
					$dealsEntity->status = 0;
					$dealsEntity->duration = $duration;
					$dealId = $this->dealsDataService->create ( $dealsEntity );
					
					// add address for Groupon/deals
					$contactAddressDataService = new ContactAddressDataService ();
					if (! empty ( $listAdds )) {
						$contactAddressEntity = $contactAddressDataService->beforeCreate ();
						foreach ( $listAdds as $add ) {
							$contactAddressEntity->groupon_id = $grouponId;
							$contactAddressEntity->groupon_address_id = $add;
							$contactAddressDataService->create ( $contactAddressEntity );
						}
					}
					//add commet
					$commentDataService = new DealCommentDataService();
					$commentEntity = $commentDataService->beforeCreate();
					$commentEntity->comment_text = $this->getPost('comment');
					$commentEntity->deal_id = $dealId;
					$commentEntity->user_id = $authentication->getCurrentUserId();
					$commentEntity->default = 1;
					$commentDataService->create($commentEntity);
					// Redirect to edit groupon
					$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Groupon/addphotos/groupon_id/' .$grouponId;
					CommonUtils::redirect ( $url );
					exit ();
				} catch ( Exception $ex ) {
					$isError = true;
					// Ignore to process this case. Only show a message
					$msg = 'Có lỗi xảy ra khi tạo';
					
					echo $ex->getMessage ();
				
				}
			} else {
				$isError = true;
				$msg = 'Sai hoặc thiếu dữ liệu';
			}
		}
		
		$this->smarty->assign ( 'arrCatList', $this->grouponCategoryDataService->getCategoryList ( 0, NULL, $this->grouponCategoryDataService->tabSpace ) );
		$supplierDataService = new SupplierDataService();
		$this->smarty->assign('arrSupList', $supplierDataService->getItems(array()));

		// Create new token key
		$this->createActionKey ();
		
		//$this->smarty->assign ( 'msg', $msg );
		//$this->smarty->assign ( 'isError', $isError );
		
		$this->smarty->assign ( 'aError', $aError);
		$this->smarty->assign ( 'bError', $bError );
		
		//groupon
		$this->smarty->assign ( 'title', isset ( $title ) ? $title : "" );
		$this->smarty->assign ( 'description', isset ( $description ) ? $description : "" );
		$this->smarty->assign ( 'groupon_name', isset ( $groupon_name ) ? $groupon_name : "" );
		$this->smarty->assign ( 'category', isset ( $category_id ) ? $category_id : 0 );
		$this->smarty->assign ( 'supplier', isset ( $supplier_id ) ? $supplier_id : 0 );
		$this->smarty->assign ( 'hightlight', isset ( $hightlight ) ? $hightlight : "" );
		//deal
		$this->smarty->assign ( 'fine_print', isset ( $fine_print ) ? $fine_print : "" );
		$this->smarty->assign ( 'original_price', isset ( $original_price ) ? $original_price : false );
		$this->smarty->assign ( 'sale_price', isset ( $sale_price ) ? $sale_price : false );
		$this->smarty->assign ( 'min_bought', isset ( $min_bought ) ? $min_bought : "" );
		$this->smarty->assign ( 'max_bought', isset ( $max_bought ) ? $max_bought : "" );
		$this->smarty->assign ( 'duration', isset ( $duration ) ? $duration : "" );
		
		$grouponAddressDataService = new GrouponAddressDataService ();
		$listAddress = $grouponAddressDataService->getItems ( array () );
		$this->smarty->assign ( 'listAddress', $listAddress );
		
		$this->userDataService = new UserDataService ();
		$this->smarty->assign ( 'userDataService', $this->userDataService );
		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Groupon/add.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Edit action is trigger when admin want to edit the groupon_category information
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function editAction() {
		// Error flag
		$isError = false;
		$msg = "";
		
		// Get id of groupon
		$id = $this->getPost ( 'id' );
		if (empty ( $id )) {
			$id = $this->getQuery ( 'id' );
		}
		$grouponEntity = $this->grouponDataService->getById($id);
		if($this->getPost('save', '') != ''){
			$groupon_name = $this->getPost('groupon_name', '');
			$title = $this->getPost('title', '');
			$supplier_id = $this->getPost('supplier_id', '');
			$category_id = $this->getPost('category_id', '');
			$description = $this->getPost('description', '');
			$hightlight = $this->getPost('hightlight', '');
			
			$grouponEntity->groupon_name = $groupon_name;
			$grouponEntity->title = $title;
			$grouponEntity->supplier_id = $supplier_id;
			$grouponEntity->category_id = $category_id;
			$grouponEntity->description = $description;
			$grouponEntity->hightlight = $hightlight;
			
			$a = $this->grouponDataService->update($grouponEntity);
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Groupon/';
			CommonUtils::redirect ( $url );
		}
		
		$this->smarty->assign ( 'arrCatList', $this->grouponCategoryDataService->getCategoryList ( 0, NULL, $this->grouponCategoryDataService->tabSpace ) );
		$supplierDataService = new SupplierDataService();
		$this->smarty->assign('arrSupList', $supplierDataService->getItems(array()));
		$this->smarty->assign('groupon', $grouponEntity);
		$this->smarty->display ('Admin/Groupon/edit.tpl' );
	}
	
	/**
	 * Delete action is trigger when administrator want to delete a groupon_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function deleteAction() {
		// Get Id of groupon
		$id = $this->getPost ( 'idValue', 0 );
		
		if ($this->validateActionKey () && ! empty ( $id ) && is_numeric ( $id )) {
			
			$id = intval ( $id );
			// Delete groupon
			$res = $this->grouponDataService->del ( $id );
		}
		$this->listAction ();
	}
	public function upphotoAction() {
		$picture = '';
		try {
			$picture = CommonUtils::uploadPictureEx ( 'uploadfile' );
			echo "success";
		} catch ( Exception $ex ) {
			// Ignore this case
			$resultMessage = 'Upload image fail.';
		}
		echo "error file size > 1 MB";
	}
	public function addphotosAction(){
		$actionForm = $this->getPost('submit', '' );
		if ($actionForm == 'Upload') {
			$groupon_id = $this->getQuery ( 'groupon_id' , 0);
			echo $groupon_id;
			$grouponEntity = $this->grouponDataService->getById($groupon_id);
			$picture = $grouponEntity->picture;
			try {
				for($i = 1; $i<=10; $i++){
					$url = CommonUtils::uploadPictureEx ( 'photo_'.$i );
					if($url != ''){
						$picture .= ',' . $url;
					}
				}
			} catch ( Exception $ex ) {
				
			}
			$grouponEntity->picture = $picture;
			$res =  $this->grouponDataService->update($grouponEntity);
			// Redirect to edit groupon
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Groupon/';
			CommonUtils::redirect ( $url );
			exit ();
		}
		$this->smarty->assign('groupon_id', $this->getQuery('groupon_id', 0));
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Groupon/addphotos.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
}
